(async function () {
  /**
   * 从网络获取歌词数据
   * @returns {Promise} 歌词字符串
   */
  async function getLrc() {
    return await fetch("https://study.duyiedu.com/api/lyrics")
      .then((resp) => resp.json())
      .then((resp) => resp.data);
  }

  const doms = {
    ul: document.querySelector(".lrc"),
    audio: document.querySelector("audio"),
  };
  const size = {
    liHeight: 30,
    containerHeight: 420,
  };

  let lrcData;

  // 1. 初始化
  async function init() {
    const lrc = await getLrc();
    lrcData = lrc
      .split("\n")
      .filter((v) => v)
      .map((s) => {
        const [first, words] = s.split("]");
        const time = first.slice(1).split(":");

        return {
          time: time[0] * 60 + +time[1],
          words,
        };
      });

    doms.ul.innerHTML = lrcData.map((v) => `<li>${v.words}</li>`).join("");
  }

  await init();

  // 2. 交互事件
  doms.audio.addEventListener("timeupdate", function () {
    setStatus(this.currentTime);
  });

  function setStatus(time) {
    // 微调（歌词太慢）
    time += 0.5;

    const activeLi = document.querySelector(".active");
    activeLi && activeLi.classList.remove("active");

    const index = lrcData.findIndex((v) => v.time >= time) - 1;
    if (index < 0) return;

    doms.ul.children[index].classList.add("active");

    const top = Math.min(
      0,
      -(size.liHeight * index + size.liHeight / 2 - size.containerHeight / 2)
    );

    doms.ul.style.transform = `translate(0, ${top}px)`;
  }
})();
